package com.py.purchase.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.py.api.PyCodeApi;
import com.py.purchase.domain.*;
import com.py.purchase.message.MessageProducer;
import com.py.purchase.service.IPyAttachmentService;
import com.py.purchase.service.ProductInfoResultService;
import com.py.purchase.vo.Message;
import com.ruoyi.common.security.utils.SecurityUtils;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.py.purchase.service.IOdPurchaseOrderService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 进货订单Controller
 * 
 * @author 童佳
 * @date 2024-11-21
 */
@RestController
@RequestMapping("/purchase")
public class OdPurchaseOrderController extends BaseController
{
    @Resource
    private IOdPurchaseOrderService odPurchaseOrderService;

    @Resource
    private IPyAttachmentService pyAttachmentService;

    @Resource
    private ProductInfoResultService productInfoResultService;

    @Resource
    private PyCodeApi pyCodeApi;

    @Resource
    private MessageProducer messageProducer;

    /**
     * 获取编码
     */
    @PostMapping("/getcode")
    public Map<String, Object> getCode(@RequestParam(value = "code",required = false) Integer code){
        System.out.println("进来了"+code);
        return pyCodeApi.generateCode(code);
    }

    /**
     * 查询进货部门
     */
    @GetMapping("/selectAllSysDept")
    public List<SysDept> selectAllSysDept(){
      /*  System.out.println("jisss");
        List<SysDept> list=odPurchaseOrderService.selectAllSysDept();
        list.forEach(System.out::println);*/
        return odPurchaseOrderService.selectAllSysDept();
    }

    /**
     * 查询进货部门
     */
    @GetMapping("/selectAllSysDeptByID")
    public List<SysDept> selectAllSysDeptByID(@RequestParam("deptid") Long deptid){
      /*  System.out.println("进；俺宿舍"+deptid);
        List<SysDept> list=odPurchaseOrderService.selectAllSysDeptByParentId(deptid);
        list.forEach(System.out::println);*/
        return odPurchaseOrderService.selectAllSysDeptByParentId(deptid);
    }

    /**
     * 根据部门id查用户
     */
    @RequestMapping("/selectUserById")
    public List<SysUser> selectUserById(@RequestParam("deptid") Long deptid){
       /* System.out.println("进来了"+deptid);
        List<SysUser> list=odPurchaseOrderService.selectAllSysUser(deptid);
        list.forEach(System.out::println);*/
        return odPurchaseOrderService.selectAllSysUser(deptid);
    }

    /**
     * 查询进货订单列表
     */
    @RequiresPermissions("purchase:purchase:list")
    @GetMapping("/list")
    public TableDataInfo list(OdPurchaseOrder odPurchaseOrder)
    {
        startPage();
        List<OdPurchaseOrder> list = odPurchaseOrderService.selectOdPurchaseOrderList(odPurchaseOrder);
        System.out.println("list:"+getDataTable(list).toString());
        return getDataTable(list);
    }

    /**
     * 导出进货订单列表
     */
    @RequiresPermissions("purchase:purchase:export")
    @Log(title = "进货订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OdPurchaseOrder odPurchaseOrder)
    {
        List<OdPurchaseOrder> list = odPurchaseOrderService.selectOdPurchaseOrderList(odPurchaseOrder);
        ExcelUtil<OdPurchaseOrder> util = new ExcelUtil<OdPurchaseOrder>(OdPurchaseOrder.class);
        util.exportExcel(response, list, "进货订单数据");
    }

    /**
     * 获取进货订单详细信息
     */
    @RequiresPermissions("purchase:purchase:query")
    @GetMapping(value = "/{phId}")
    public AjaxResult getInfo(@PathVariable("phId") Integer phId)
    {
        System.out.println("phid:"+phId);
        return success(odPurchaseOrderService.selectOdPurchaseOrderByPhId(phId));
    }

    /**
     * 新增进货订单
     */
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("purchase:purchase:add")
    @Log(title = "进货订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OdPurchaseOrder odPurchaseOrder)
    {
        System.out.println("odPurchaseOrder："+odPurchaseOrder);
        System.out.println("number:"+odPurchaseOrder.getNumber());
        System.out.println("codeId:"+odPurchaseOrder.getCodeId());
        pyCodeApi.saveCode(odPurchaseOrder.getCodeId(),odPurchaseOrder.getNumber());
        odPurchaseOrder.setCreateBy(SecurityUtils.getUsername());
        SysUser sysUser=odPurchaseOrderService.selectBySysUserName(SecurityUtils.getUsername());
        odPurchaseOrder.setCreateDept(sysUser.getDeptName());
        odPurchaseOrder.setCreateTime(new Date());
        List<Object> fileList = odPurchaseOrder.getFileList();
        if(fileList.size()>0){
            for (Object file : fileList) {
                if (file instanceof Map) {
                    Map<String, Object> fileMap = (Map<String, Object>) file;
                    Map<String, Object> response = (Map<String, Object>) fileMap.get("response");
                    Object ob=fileMap.get("size");
                    if (response != null) {
                        Map<String, Object> data = (Map<String, Object>) response.get("data");
                        if (data != null) {
                            String name = (String) data.get("name");
                            String url = (String) data.get("url");
                            System.out.println("Name: " + name);
                            System.out.println("URL: " + url);
                            PyAttachment pyAttachment=new PyAttachment();
                            pyAttachment.setBusinessType("进货单");
                            pyAttachment.setOwnershipNumber(odPurchaseOrder.getPhCode());
                            pyAttachment.setFileName(name);
                            pyAttachment.setSize(Long.parseLong(ob.toString()));
                            pyAttachment.setFilePath(url);
                            pyAttachmentService.insertPyAttachment(pyAttachment);
                        }
                    }
                }
            }
        }
        // 遍历 fileList
        messageProducer.sendMessageDirect("新增了一个进货单: "+odPurchaseOrder.getPhCode()+" 待审核!");
        return toAjax(odPurchaseOrderService.insertOdPurchaseOrder(odPurchaseOrder));
    }

    /**
     * 修改进货订单
     */
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("purchase:purchase:edit")
    @Log(title = "进货订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OdPurchaseOrder odPurchaseOrder)
    {
        odPurchaseOrder.setUpdateBy(SecurityUtils.getUsername());
        odPurchaseOrder.setUpdateTime(new Date());
        pyAttachmentService.deletePyAttachmentByOwnershipNumber(odPurchaseOrder.getPhCode());
        List<Object> fileList = odPurchaseOrder.getFileList();
        if (fileList.size() > 0) {
            System.out.println("进来了11111111111111");
            for (Object file : fileList) {
                if (file instanceof Map) {
                    Map<String, Object> fileMap = (Map<String, Object>) file;
                    String name = (String) fileMap.get("name");
                    String url = (String) fileMap.get("url");
                    Object size = fileMap.get("size");

                    // 如果 name 和 url 不为空，直接使用
                    if (name != null && url != null) {
                        System.out.println("Name: " + name);
                        System.out.println("URL: " + url);
                        PyAttachment pyAttachment = new PyAttachment();
                        pyAttachment.setBusinessType("进货单");
                        pyAttachment.setOwnershipNumber(odPurchaseOrder.getPhCode());
                        pyAttachment.setFileName(name);
                        pyAttachment.setSize(Long.parseLong(size.toString()));
                        pyAttachment.setFilePath(url);
                        pyAttachmentService.insertPyAttachment(pyAttachment);
                        continue;
                    }

                    // 如果 name 或 url 为空，尝试从 response 中获取
                    Map<String, Object> response = (Map<String, Object>) fileMap.get("response");
                    if (response != null) {
                        Map<String, Object> data = (Map<String, Object>) response.get("data");
                        if (data != null) {
                            name = (String) data.get("name");
                            url = (String) data.get("url");
                            if (name != null && url != null) {
                                System.out.println("Name: " + name);
                                System.out.println("URL: " + url);
                                PyAttachment pyAttachment = new PyAttachment();
                                pyAttachment.setBusinessType("进货单");
                                pyAttachment.setOwnershipNumber(odPurchaseOrder.getPhCode());
                                pyAttachment.setFileName(name);
                                pyAttachment.setSize(Long.parseLong(size.toString()));
                                pyAttachment.setFilePath(url);
                                pyAttachmentService.insertPyAttachment(pyAttachment);
                            }
                        }
                    }
                }
            }
        }
        return toAjax(odPurchaseOrderService.updateOdPurchaseOrder(odPurchaseOrder));
    }

    /**
     * 删除进货订单
     */
    @RequiresPermissions("purchase:purchase:remove")
    @Log(title = "进货订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{phIds}")
    public AjaxResult remove(@PathVariable Integer[] phIds)
    {
        for (Integer phId : phIds){
            System.out.println("删除订单的phIds:"+phId);
        }
        return toAjax(odPurchaseOrderService.deleteOdPurchaseOrderByPhIds(phIds));
    }

    //审核
    @RequiresPermissions("purchase:purchase:check")
    @RequestMapping("/check")
    public AjaxResult check(@RequestBody Map<String,Object> map){
        System.out.println("审核的phIds:"+map);
        Map<String,Object> map1=new HashMap<>();
        map1.put("reviewer", SecurityUtils.getUsername());
        map1.put("reviewer_time",new Date());
        if((String)map.get("comments")!=null){
            map1.put("reviewer_report",map.get("comments").toString());
        }
        map1.put("ph_state",map.get("result").toString());
        List<Integer> list= (List<Integer>) map.get("phId");
        list.forEach(System.out::println);
        map1.put("ph_id",list);
      /*  int i=ShenHe(new Integer[]{(Integer) map.get("phId")});
        System.out.println("是否成功修改:"+i);*/
        return toAjax(odPurchaseOrderService.checkById(map1));
    }

   /* public int ShenHe(Integer[] phid)
    {
        System.out.println("进来了："+phid);
        //根据ID 查询订单
        for (Integer integer:phid){
            OdPurchaseOrder odPurchaseOrder=odPurchaseOrderService.selectOdPurchaseOrderByPhId(integer);

            System.out.println("单号："+odPurchaseOrder);
            //根据编号查Message id
            Message message= productInfoResultService.selectMessage(odPurchaseOrder.getPhCode());

            System.out.println("message:"+message);

            int i=productInfoResultService.udpateState(message.getId());

            System.out.println("修改状态:"+i);

            if (i>0){
                messageProducer.sendMessage(odPurchaseOrder.getPhCode()+"审核成功");
            }
        }

        //修改状态
        return i;
    }*/


    @RequiresPermissions("purchase:purchase:revoke")
    @RequestMapping("/revoke")
    public AjaxResult revoke(@RequestParam("phid") Integer phid){
        System.out.println("撤回的phid:"+phid);
        return toAjax(odPurchaseOrderService.revokeById(phid));
    }

    @RequestMapping("/fileInfo")
    public Map<String,Object> fileInfo(@RequestParam("phcode") String phcode){
        Map<String,Object> map=new HashMap<>();
        PyAttachment pyAttachment=new PyAttachment();
        pyAttachment.setOwnershipNumber(phcode);
        map.put("fileList",pyAttachmentService.selectPyAttachmentList(pyAttachment));
        map.put("orderInfo",productInfoResultService.selcteProductInfoResult(phcode));
        return map;
    }


    @RequestMapping("/findOdPurchase")
    public TableDataInfo findOdPurchase(@RequestBody OdPurchaseOrder odPurchaseOrder)
    {
        System.out.println("进货退货单中的进货单："+odPurchaseOrder);
        startPage();
        List<OdPurchaseOrder> list = odPurchaseOrderService.selectOdPurchaseOrderByInRejected(odPurchaseOrder);
        return getDataTable(list);
    }

    @RequiresPermissions("purchase:purchase:close")
    @RequestMapping("/colseById")
    public AjaxResult colseById(@RequestParam("phid") Integer phid ){
        return toAjax(odPurchaseOrderService.colseById(phid));
    }

    @RequestMapping("/selectByCode")
    public Map<String,Object> selectByCode(@RequestParam("phCode") String phCode){

        OdPurchaseDetails odPurchaseDetails=new OdPurchaseDetails();
        odPurchaseDetails.setPhCode(phCode);
        List<OdPurchaseDetails> list=odPurchaseOrderService.selectOdPurchaseDetailsList(odPurchaseDetails);
        Map<String,Object> map=new HashMap<>();
        map.put("list",list);
       return  map;
    }

    @RequestMapping("/selectByPhCode")
    public Map<String,Object> selectByPhCode(@RequestParam("phCode") String phCode){
        System.out.println("selectByPhCode:"+phCode);
        return odPurchaseOrderService.selectByPhCode(phCode);
    }

}
